package com.szty.mod_jyzs.ui.questionExplain

import android.Manifest
import android.app.Activity
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.content.pm.PackageManager
import android.content.res.ColorStateList
import android.media.projection.MediaProjectionManager
import android.os.Bundle
import android.os.IBinder
import android.view.KeyEvent
import android.widget.FrameLayout
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.viewpager.widget.ViewPager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.gyf.immersionbar.ImmersionBar
import com.sjh.baseutils.color
import com.sjh.baseutils.toast
import com.sjh.lib_app.baseui.BaseActivity
import com.sjh.lib_app.HintMessageUtils
import com.sjh.lib_app.bean.QuestionExplainBean
import com.sjh.lib_app.bean.Request
import com.sjh.lib_app.net.post
import com.sjh.lib_app.router.route
import com.szty.lib_pen.oidbluetooth.BluetoothLEService
import com.szty.lib_pen.oidbluetooth.OnDataReceiveListener
import com.szty.lib_pen.oss.OssHelper
import com.szty.mod_jyzs.R
import com.szty.mod_jyzs.ui.pop.HintSavePop
import com.szty.mod_jyzs.ui.pop.SettingPenPop
import com.tqltech.tqlpencomm.bean.Dot
import katex.hourglass.`in`.mathlib.MathView
import kotlinx.android.synthetic.main.jyzs_activity_explain_question.*
import org.json.JSONObject
import java.io.File

@Route(path = "/jyzs/explainQuestion", name = "web页")
class ExplainQuestionActivity : BaseActivity() {
    private val REQUEST_CODE = 1
    private var mBleService: BluetoothLEService? = null //蓝牙服务
    private var nowShowPageIndex = 0
    private var nowMathView: MathView? = null
    private var nowEraserPenView: EraserPenView? = null
    private var penMode = EraserPenView.EDIT_MODE_PEN
    private var selectColor = R.color.app_bg_D9021B
    private var lastClickTime = 0L
    private var selectLineWidth = 2
    private val pagerAdapter by lazy {
        QuickPagerAdapter<FrameLayout>(arrayListOf())
    }
    private val screenRecordUtils by lazy {
        ScreenRecordUtils(this)
    }
    private val hintSavePop by lazy {
        HintSavePop(this) { hintSavePop ->
            screenRecordUtils.stopScreenRecord()
            uploadFileToOss()
        }
    }

    @Autowired(desc = "这是网页进入页面时传递的题目id参数是一个json", required = false)
    @JvmField
    var jsonParams: String = ""
    val questionId by lazy {
        JSONObject(jsonParams)["id"]
    }
    private val mMediaProjectionManager by lazy {
        getSystemService(MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
    }
    private val settingPop by lazy {
        SettingPenPop(this) { color: Int, lineWidth: Int ->
            selectLineWidth = lineWidth
            selectColor = color
            initPenStatus()
        }
    }

    private fun uploadFileToOss() {
        OssHelper.getInstance().upLoadFile(
            screenRecordUtils.filePath,
            questionId.toString(),
            process = { hintSavePop.refurbishProgress(it) },
            upLoadResult = {
                runOnUiThread {
                    if (it) {
                        "视频上传成功".toast()
                        File(screenRecordUtils.filePath).delete()
                        finish()
                    } else {
                        hintSavePop.switchShowPage(1)
                        hintSavePop.refUpLoadProgress()
                        "视频上传失败,请重新上传".toast()
                    }
                }
            })
    }


    private fun initPenStatus() {
        nowEraserPenView?.setPenWidth(selectLineWidth.toFloat())
        nowEraserPenView?.setPenColor(selectColor)
        nowEraserPenView?.setMode(penMode)
        nowEraserPenView?.isCanWrite =
            screenRecordUtils.screenRecordStatus == ScreenRecordUtils.RUNNING
    }

    private val onDataReceiverListener by lazy {
        object : OnDataReceiveListener() {
            override fun onDataReceive(dot: Dot?) {
                if (dot == null) return
                runOnUiThread {
                    nowEraserPenView?.processEachDot(dot)
                }
            }

            override fun onConnectChange(status: Int) {
                super.onConnectChange(status)
                changeStatus(status == 1)
            }
        }
    }
    private val mServiceConnection by lazy {
        object : ServiceConnection {
            override fun onServiceDisconnected(name: ComponentName?) {}
            override fun onServiceConnected(name: ComponentName, service: IBinder) {
                if (service is BluetoothLEService.LocalBinder) {
                    mBleService = service.service
                }
                mBleService?.apply {
                    addOnDataReceiveListener(onDataReceiverListener)
                }
            }
        }
    }

    private fun changeStatus(isChangePenStatus: Boolean) {
        runOnUiThread {
            img_pen_status.setBackgroundResource(if (isChangePenStatus) R.drawable.sp_bg_round_blue else R.drawable.sp_bg_round_red)
        }
    }

    override fun onCreateRootView() = R.layout.jyzs_activity_explain_question

    override fun onInitView(savedInstanceState: Bundle?) {
        ImmersionBar.with(this)
            .fitsSystemWindows(true)
            .statusBarDarkFont(true)
            .statusBarColor(R.color.white).init()
        bindService(
            Intent(this, BluetoothLEService::class.java),
            mServiceConnection,
            Context.BIND_AUTO_CREATE
        )
        vp_parent.adapter = pagerAdapter
        vp_parent.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
                nowShowPageIndex = position
                tv_page_index.text = "${nowShowPageIndex + 1}/${pagerAdapter.count}"
                if (position == 0) {
                    img_previous.imageTintList = ColorStateList.valueOf(color(R.color.black))
                } else {
                    img_previous.imageTintList =
                        ColorStateList.valueOf(color(R.color.app_splash_blue))
                }
                val nowShowView = pagerAdapter.getNowShowData(position)
                initShowPage(nowShowView)
            }

            override fun onPageSelected(position: Int) {}
            override fun onPageScrollStateChanged(state: Int) {}
        })
        addPage()
    }

    /**
     * 初始化当前显示的页面控件
     * 有两件事情要做，1.替换控件，2.判断是否第一页，如果是第一页，要显示公式出来
     */
    private fun initShowPage(nowShowView: FrameLayout) {
        val tag = nowShowView.getTag(R.layout.jyzs_layout_page)
        nowMathView = nowShowView.findViewById(R.id.ktx_eraser_question1)
        if (tag is Int && tag == 0) {
            nowMathView?.resumeTimers()
            nowMathView?.settings?.builtInZoomControls = false
        }
        nowEraserPenView = nowShowView.findViewById(R.id.dv_eraser_pen_view)
        initPenStatus()
    }

    private fun uploadMediaRelease() {
        if (!File(screenRecordUtils.filePath).exists()) {
            "还未录制视频".toast()
            return
        }
        screenRecordUtils.pauseScreenRecord()
        val info = String.format(
            resources.getString(R.string.jyzs_show_time_info),
            tv_time.text.toString()
        )
        hintSavePop.showPopupWindow(info)
    }

    private fun createScreenCapture() {
        val createScreenCaptureIntent = mMediaProjectionManager.createScreenCaptureIntent()
        startActivityForResult(createScreenCaptureIntent, REQUEST_CODE)
    }
    override fun initListener() {
        img_back.setOnClickListener {
            backEvent()

        }
        img_run_or_pause.setOnClickListener {
            val nowTime = System.currentTimeMillis()
            if(nowTime - lastClickTime<1000){
                return@setOnClickListener
            }
            lastClickTime = nowTime
            when (screenRecordUtils.screenRecordStatus) {
                ScreenRecordUtils.RUNNING -> {
                    screenRecordUtils.pauseScreenRecord()
                }
                ScreenRecordUtils.PAUSE -> {
                    screenRecordUtils.resumeScreenRecord()
                }
                ScreenRecordUtils.STOP -> {
                    checkPermission()
                }
            }
        }
        screenRecordUtils.callTime = {
            tv_time.text = it
        }
        screenRecordUtils.callMaxTime = {
            val overTimeHintMessage = resources.getString(R.string.jyzs_show_over_time_info)
            hintSavePop.showPopupWindow(overTimeHintMessage, {
                File(screenRecordUtils.filePath).delete()
                finish()
            })
        }
        screenRecordUtils.callRecordStatus = {
            when (it) {
                ScreenRecordUtils.STOP -> {
                    nowEraserPenView?.isCanWrite = false
                    img_run_or_pause.setImageResource(R.mipmap.jyzs_icon_pause)
                }
                ScreenRecordUtils.PAUSE -> {
                    nowEraserPenView?.isCanWrite = false
                    img_run_or_pause.setImageResource(R.mipmap.jyzs_icon_pause)
                }
                ScreenRecordUtils.RUNNING -> {
                    nowEraserPenView?.isCanWrite = true
                    img_run_or_pause.setImageResource(R.mipmap.jyzs_icon_running)
                }
            }
        }
        img_upload.setOnClickListener {
            uploadMediaRelease()
        }
        img_pen_status.setOnClickListener {
            route("/lib_pen/devConnect")
        }
        rg_now_status.setOnCheckedChangeListener { group, checkedId ->
            when (checkedId) {
                R.id.rb_pen -> {
                    penMode = EraserPenView.EDIT_MODE_PEN
                    initPenStatus()
                }
                R.id.rb_eraser -> {
                    penMode = EraserPenView.EDIT_MODE_ERASER
                    initPenStatus()
                }
            }
        }
        rb_pen.setOnClickListener {
            settingPop.showPopupWindow()
        }
        img_previous.setOnClickListener {
            if (nowShowPageIndex != 0) {
                nowShowPageIndex--
                vp_parent.currentItem = nowShowPageIndex
            }
        }
        img_next.setOnClickListener {
            if (nowShowPageIndex >= pagerAdapter.count - 1) {
                addPage()
            } else {
                nowShowPageIndex++
                vp_parent.currentItem = nowShowPageIndex
            }
        }
    }

    private fun backEvent() {
        if (File(screenRecordUtils.filePath).exists()) {
            if (screenRecordUtils.screenRecordStatus == ScreenRecordUtils.RUNNING) screenRecordUtils.pauseScreenRecord()
            val info = String.format(
                resources.getString(R.string.jyzs_show_time_finish_info),
                tv_time.text.toString()
            )
            hintSavePop.showPopupWindow(info, {
                File(screenRecordUtils.filePath).delete()
                finish()
            }, isCanClickOutSidDismiss = true)
            return
        }
        finish()
    }

    private fun addPage() {
        val inflate = layoutInflater.inflate(R.layout.jyzs_layout_page, null)
        if (inflate is FrameLayout) {
            pagerAdapter.addPage(inflate)
            inflate.setTag(R.layout.jyzs_layout_page, nowShowPageIndex)
        }
        vp_parent.currentItem = pagerAdapter.count - 1
    }

    override fun initData() {
        post<Request<Array<QuestionExplainBean>>> {
            url = "/helper/paper/question-detail"
            params = {
                "question_id[0]" to questionId.toString()
            }
            onResult =
                { s: String, result: Request<Array<QuestionExplainBean>>, b: Boolean, i: Int ->
                    if (result.isSuccess) {
                        result.data?.forEach {
                            nowMathView?.setDisplayText(it.title)
                        }
                    }
                }
        }
    }

    fun checkPermission() {
        var requestPermissionResult =
            ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.RECORD_AUDIO
            ) + ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
        if (requestPermissionResult != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(
                    Manifest.permission.READ_PHONE_STATE,
                    Manifest.permission.RECORD_AUDIO
                ),
                123
            )
        } else {
            createScreenCapture()
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode != 123) return
        var requestResult = 0
        grantResults.forEach {
            requestResult += it
        }
        if (requestResult == PackageManager.PERMISSION_GRANTED) {
            createScreenCapture()
        } else {
            HintMessageUtils.showHintMessage(false, "只有同意了权限，才能使用录制功能")
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            try {
                data!!.putExtra("resultCode", resultCode)
                screenRecordUtils.startScreenRecord(data)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        backEvent()
        return true
    }
}